//
//  HotViewController.m
//  GiftSay
//
//  Created by dllo on 16/1/6.
//  Copyright © 2016年 liyinkai. All rights reserved.
//

#import "HotViewController.h"

@interface HotViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) UICollectionView *collection;
#pragma mark 下拉动画
@property (nonatomic,strong) Animal *animal;

@property (nonatomic,strong) NSMutableArray *itemsArray;
@property (nonatomic,assign) NSInteger number;

@property (nonatomic,assign) CGFloat contenty;

@end

static int scrolltimes = 0;

@implementation HotViewController


- (void)viewWillAppear:(BOOL)animated
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"NightMode"] == YES) {
        self.navigationController.navigationBar.barTintColor = kNightModeNavigationColor;
        self.collection.backgroundColor = kNightModeColor;
    } else {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:248 / 255.0 green:78 / 255.0 blue:78 / 255.0 alpha:1];
        self.collection.backgroundColor = [UIColor whiteColor];
    }
    [self.collection reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.number = 0;
    if (self.ids > 0) {
        self.url = [NSString stringWithFormat:kItemData, self.ids, self.number];
//        NSLog(@"%@", self.url);
    }
    
    if (self.name > 0) {
        self.title = self.name;
    } else if (self.god > 0) {
        self.title = self.name;
    } else {
        self.title = @"热门";
    }
    if (self.number || self.name > 0) {
        UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backToTactik:)];
        self.navigationItem.leftBarButtonItem = button;
    }
    self.view.backgroundColor = [UIColor colorWithWhite:0.7 alpha:1];
    
    self.itemsArray = [NSMutableArray arrayWithCapacity:0];
    
    if (self.url > 0) {
//        NSLog(@"%@", self.url);
        [self getData:self.url];
    } else if (self.god > 0) {
        NSString *url = [NSString stringWithFormat:kGodData, self.number];
        [self getData:url];
    } else {
        [self getaDatource];
    }
    
    [self createdCollectionview];
    
    self.animal = [[Animal alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.animal];
    //添加动画结束的监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(animalStop:) name:@"tag" object:nil];
    
    // Do any additional setup after loading the view.
}

#pragma mark 动画结束监听方法
- (void)animalStop:(NSNotification *)object
{
    [self.collection setContentOffset:CGPointMake(0, 0) animated:YES];
    
    self.animal.frame = CGRectMake(0, 0, 0, 0);
    self.animal.contetsize = CGSizeZero;
}

- (void)backToTactik:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 刷新
- (void)reload
{
    NSLog(@"刷新");
    if (self.itemsArray.count > 0) {
        [self.itemsArray removeAllObjects];
    }
    
    [self getaDatource];
}

#pragma mark -- 下拉刷新
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < -60) {
        [scrollView setContentOffset:CGPointMake(0, -60) animated:YES];
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y < 0) {
        NSLog(@"下拉刷新");
        
        self.animal.frame = CGRectMake(0, kHeight / 150 , self.view.width, 60);
        self.animal.contetsize = CGSizeMake(kWidth, 60);
        
        [self.animal strat];
        
        [self reload];
    }
    
}



#pragma mark 加载
- (void)addItem
{
    NSLog(@"加载");
    
    if (self.url > 0) {
        self.number += 20;
//        NSLog(@"%@", self.url);
        self.url = [NSString stringWithFormat:kItemData, self.ids, self.number];
        [self getData:self.url];
        
    } else if (self.god > 0) {
        self.number += 20;

        NSString *url = [NSString stringWithFormat:kGodData, self.number];
//        NSLog(@"%@", url);
        [self getData:url];
    } else  {
        self.number += 1;
        [self getaDatource];
    }
    
    
}

#pragma mark 本页缓存
- (void)cacheItems
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    
    NSString *cachesDirectory = [paths lastObject];

    cachesDirectory = [cachesDirectory stringByAppendingString:@"/HotItemsCache"];
    
    [self.itemsArray writeToFile:cachesDirectory atomically:YES];
    
    NSLog(@"%@",cachesDirectory);
    
}

//- (void)viewWillDisappear:(BOOL)animated
//{
//    [self cacheItems];
//}

//创建collectionview

- (void)createdCollectionview
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.sectionInset = UIEdgeInsetsMake(kWidth / 50, kWidth / 50, kWidth/50, kWidth/50);
    
    flow.minimumInteritemSpacing = kWidth / 50;
    flow.minimumLineSpacing = kWidth / 50;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.size.width, self.view.size.height - 64) collectionViewLayout:flow];
    self.collection.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    
    [self.collection registerClass:[BaseCollectionViewCell class] forCellWithReuseIdentifier:@"BaseCollectionViewCell"];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    
    [self.view addSubview:self.collection];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kWidth / 50 * 23, kHeight / 10 * 4);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  self.itemsArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BaseCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BaseCollectionViewCell" forIndexPath:indexPath];
    if (self.itemsArray.count > indexPath.row) {
        cell.item = self.itemsArray[indexPath.row];
    }
    
    return cell;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.contenty = scrollView.contentOffset.y;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.contenty) {
        if (scrollView.contentOffset.y > scrollView.contentSize.height - 700) {
            
            //加载更多数据
            if (scrolltimes == 0) {
                [self addItem];
                scrolltimes = 1;
            }
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    Items *item = self.itemsArray[indexPath.row];
    
    WebViewController *web = [[WebViewController alloc] init];
    web.url = [NSString stringWithFormat:@"%@%@",kItemsInfo,item.ID];
    //可拼接web
//    web.url = [NSString stringWithFormat:@"%@%@",kItemsInfoTow,item.ID];
//    web.type = @"itemshtml";
    
    [self.navigationController pushViewController:web animated:YES];
    
}

//获取数据
- (void)getaDatource
{
    [LYKNetWorkTool getWithUrl:[NSString stringWithFormat:@"%@%ld",kHotItemsUrl,self.number * 50] parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id result) {
//        NSLog(@"%@", result);
        id any = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
        
        NSDictionary *dicforData = [NSDictionary dictionaryWithDictionary:any[@"data"]];
        
        NSArray *items = [NSArray arrayWithArray:dicforData[@"items"]];
        
        for (NSDictionary *datasource in items) {
            
            NSDictionary *dic = datasource[@"data"];
            Items *item = [[Items alloc] init];
            item.like = [NSString stringWithFormat:@"%@",dic[@"favorites_count"]];
            item.ID = [NSString stringWithFormat:@"%@",dic[@"id"]];
            item.cover_icon = dic[@"cover_image_url"];
            item.title = dic[@"name"];
            item.price = [NSString stringWithFormat:@"%@",dic[@"price"]];
            
            [self.itemsArray addObject:item];
        }
        
//        NSLog(@"%ld",self.itemsArray.count);
        
        [self.collection reloadData];
        scrolltimes = 0;
        
    } fail:^(NSError *erro) {
        
    }];
}

- (void)getData:(NSString *)url {
    [LYKNetWorkTool getWithUrl:url parameter:nil httpHeader:nil resposeType:ResponseTypeDATA success:^(id(success)) {
//        NSLog(@"%@", success);
        id any = [NSJSONSerialization JSONObjectWithData:success options:0 error:nil];
        
        NSDictionary *dicforData = [NSDictionary dictionaryWithDictionary:any[@"data"]];
        
        
        NSArray *items = [NSArray arrayWithArray:dicforData[@"items"]];
        
        for (NSDictionary *datasource in items) {
          //到此数据丢失
//            NSDictionary *dic = datasource[@"data"];
//            NSLog(@"🐶%@", dic);
            Items *item = [[Items alloc] init];
//            [item setValuesForKeysWithDictionary:datasource];
            item.like = [NSString stringWithFormat:@"%@",datasource[@"favorites_count"]];
//            NSLog(@"%@", item.like);
            item.ID = [NSString stringWithFormat:@"%@",datasource[@"id"]];
            item.cover_icon = datasource[@"cover_image_url"];
            item.title = datasource[@"name"];
            item.price = [NSString stringWithFormat:@"%@",datasource[@"price"]];
            
            [self.itemsArray addObject:item];
        }
        
//        NSLog(@"%ld",self.itemsArray.count);
        
        [self.collection reloadData];
        
        scrolltimes = 0;
    } fail:^(NSError *erroe) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
